package com.cloud.service.wxtemplatemessage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.commons.constants.ConsumeConstant;
import com.cloud.commons.utils.DateUtils;
import com.cloud.commons.utils.wechat.WeixinUtil;
import com.cloud.dao.consumetype.ConsumeTypeDao;
import com.cloud.dao.wxuser.WxUserDao;
import com.cloud.model.entity.consumetype.ConsumeType;
import com.cloud.model.entity.wxmintemplateproject.WxMinTemplateProject;
import com.cloud.model.entity.wxuser.WxUser;
import com.cloud.model.view.bookkeeping.BookkeepingView;
import com.cloud.service.accesstoken.AccessTokenService;
import com.cloud.service.wxtemplatemessage.WxTemplateMessageService;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class WxTemplateMessageSerivceImpl implements WxTemplateMessageService {

    private static final Logger LOG = LoggerFactory.getLogger(WxTemplateMessageSerivceImpl.class);

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ConsumeTypeDao consumeTypeDao;

    @Override
    public void bookkeepingSuccessMessage(BookkeepingView bookkeepingView, WxUser wxUser){
        // 订阅id
        String templateId = "nlD1JNUEtWlHjUiqcNFOYJQBG-akvOSbST0b0aWllOs";
        // 校验必填参数是否完善
        if (ObjectUtils.isEmpty(wxUser.getId())) {
            throw new RuntimeException("模板消息发送失败，必填参数缺少");
        }
        // userId
        Long userId = wxUser.getId();
        // 设置跳转页面
        String page = "pages/index/authoriztion/authoriztion?form=bookkeepingDetail&bookkeepingid=" + bookkeepingView.getId();
        // 设置模板消息内容
        List<String> keywordValues = new ArrayList<>();
        // 记账时间
        String nowTime = DateUtils.timeStamp2Date(String.valueOf(bookkeepingView.getConsumeTime()), ConsumeConstant.DATE_FORMAT);
        keywordValues.add(nowTime);
        // 记账类型
        ConsumeType consumeType = consumeTypeDao.findById(bookkeepingView.getConsumeTypeId()).orElseThrow(() -> new RuntimeException("获取不到记账类型id为：" + bookkeepingView.getConsumeTypeId() + "的数据信息"));
        String orderType = consumeType.getName();
        keywordValues.add(orderType);
        // 金额
        String money = String.valueOf(bookkeepingView.getMoney() / 100) + "元";
        keywordValues.add(money);
        // 记账人
        String bookkeepingBeople = wxUser.getNickName();
        keywordValues.add(bookkeepingBeople);
        // 消费详情
        String consumeDetail = "您在" + bookkeepingView.getAddress()  + "花费了" + bookkeepingView.getMoney() /100+ "元";
        keywordValues.add(consumeDetail);

        // 进行发送模板消息
        sendTemplateMessage(templateId, userId, page, keywordValues);
    }

    @Override
    public void accountingBudgetMessage(BookkeepingView bookkeepingView, WxUser wxUser, Long monthTotalExpenditure) {
        // 订阅id
        String templateId = "9idG4F8CNOaiGOo5EYwqB4wxVx8QXtoSg1HjNMnlM4M";
        // 校验必填参数是否完善
        if (ObjectUtils.isEmpty(wxUser.getId())) {
            throw new RuntimeException("模板消息发送失败，必填参数缺少");
        }
        // userId
        Long userId = wxUser.getId();
        // 设置跳转页面
        String page = "pages/index/authoriztion/authoriztion?form=me&userId=" + userId;
        // 设置模板消息内容
        List<String> keywordValues = new ArrayList<>();
        // 记账时间
        String nowTime = DateUtils.timeStamp2Date(String.valueOf(bookkeepingView.getConsumeTime()), ConsumeConstant.DATE_FORMAT);
        keywordValues.add(nowTime);
        // 记账类型
        keywordValues.add("月预算");
        // 剩余预算金额
        String money = (wxUser.getMonthBudget().intValue()  -  monthTotalExpenditure.intValue()) / 100 + "元";
        keywordValues.add(money);
        // 温馨提示
        String tips = "";
        if (wxUser.getMonthBudget().intValue()  -  monthTotalExpenditure.intValue() > 0) {
            tips = "您的预算即将耗尽，请注意合理消费";
        } else {
            tips = "您的预算已耗尽，请注意合理消费";
        }

        keywordValues.add(tips);

        // 进行发送模板消息
        sendTemplateMessage(templateId, userId, page, keywordValues);

    }

    private JSONObject sendTemplateMessage(String templateId, Long userId, String page, List<String> keywordValues){
        // accesstoken
        String accessToken = accessTokenService.getAccessToken();
        // 设置openid
        Optional<WxUser> wxUserOptional = wxUserDao.findById(userId);
        WxUser wxUser = wxUserOptional.orElseThrow(() -> new RuntimeException("模板消息发送失败 获取不到用户id为" + userId + "的数据"));
        String openId = wxUser.getOpenId();

        JSONObject jsonObjectResult = null;
        try {
            // 进行封装
            WxMinTemplateProject wxMinTemplateProject = new WxMinTemplateProject(templateId,openId,page,keywordValues);

            // 获取模板消息所需要的id
            JSONObject resultTemplateProject = WeixinUtil.setMiniProgramTemplateData(wxMinTemplateProject);

            // 请求回来的数据信息
            String resultData = WeixinUtil.sendMiniProgramTemplate(accessToken, resultTemplateProject);

            LOG.info("这个是请求订阅消息回来的数据信息:" + JSON.toJSONString(resultData));

            jsonObjectResult = JSON.parseObject(resultData);

            if (jsonObjectResult.getString("errcode").equals("0")) {
                LOG.info("模板消息发送成功啦！！发送的对象openId是：" + openId);
            }
        } catch (Exception e) {
            LOG.error("模板消息发送失败！！！" + e.getMessage());
        }

        return jsonObjectResult;
    }
}
